__all__=[
    "get_distro"
]

import aptsources
import aptsources.distro
from subprocess import Popen, PIPE
import errno
import logging


debian_codename = {
    5: "lenny",
    6: "squeeze",
    7: "wheezy",
    8: "jessie",
    9: "stretch",
    10: "buster",
    11: "bullseye"
}

def _debian_version_to_codename(version_str):
    main_version = int(version_str.split('.')[0])
    codename=debian_codename[main_version]
    return codename

def _get_debian_release_version():
    result = 'unstable'
    try:
        out = Popen(['cat', '/etc/debian_version'], stdout=PIPE).communicate()[0]
        # Convert to unicode string, needed for Python 3.1
        out = out.decode("utf-8").strip()
        # result.update(l.split(":\t") for l in out.split("\n") if ':\t' in l)
        result=out
    except OSError as exc:
        if exc.errno != errno.ENOENT:
            logging.warning('cat /etc/debian_version, using defaults:' % exc)
    return result



def get_distro():
    distributor_id="Debian"
    release = _get_debian_release_version()
    codename=_debian_version_to_codename(release)
    description="Debian GNU/Linux %s (%s)" % (release, codename)
    distro = aptsources.distro.get_distro(
        id=distributor_id,
        description=description,
        release=release,
        codename=codename
    )
    return distro


if __name__=="__main__":
    print(get_distro().__dict__)